#include "mainwindow.h"
#include "ui_mainwindow.h"

#include <QDir>
#include <QDebug>
#include <QMessageBox>
#include <QFileDialog>

#include "inja/inja.hpp"
using namespace inja;
using json = nlohmann::json;


MainWindow::MainWindow(QWidget *parent)
    : QMainWindow(parent)
    , ui(new Ui::MainWindow)
{
    ui->setupUi(this);

    ui->widget_PtotovolEditor->setEnabled(false);
    connect(ui->widget_PtotovolEditor, &ProtocolEditForm::nameChanged,
            this, &MainWindow::protocolItemNameChanged);

    // 加载上次文件
    QString strFileName = Global::instance()->lastFileName();
    openGenFile(strFileName, true);
}

MainWindow::~MainWindow()
{
    delete ui;
}

// 新建协议
void MainWindow::on_actionNew_triggered()
{
    SettingDialog settingDialog;
    int res = settingDialog.exec();
    if(res == QFileDialog::Accepted)
    {

    }
}

// 添加一个节点
void MainWindow::on_actionAdd_triggered()
{
    static int newItemCount = 0;
    newItemCount ++;

    struProtocolItem protocolItem;
    protocolItem.strName = QString("NewItem%1").arg(newItemCount);
    protocolItem.strNote = QString("新节点%1").arg(newItemCount);
    protocolItem.iCode = 0xFF;
    protocolItem.bArray = false;
    protocolItem.iArrayCount = 1;
    protocolItem.bPrivate = false;
    protocolItem.access = eParamOptionAccess::PO_ReadWrite;

    m_Protocol.addItem(protocolItem);

    ui->listWidget_ProtocolItemList->addItem(QString("%1(%2)").arg(protocolItem.strNote).arg(protocolItem.strName));
    if(ui->listWidget_ProtocolItemList->currentRow() < 0)
    {
        ui->listWidget_ProtocolItemList->setCurrentRow(0);
    }
}

// 删除一个节点
void MainWindow::on_actionDelete_triggered()
{
    int n = ui->listWidget_ProtocolItemList->currentRow();
    if(n < 0)
    {
        return;
    }

    struProtocolItem protocolItem = m_Protocol.itemAt(n);
    int res = QMessageBox::question(this,
                          "提示",
                          QString("是否删除协议节点 %1").arg(protocolItem.strNote),
                          QMessageBox::Ok|QMessageBox::Cancel);
    if(res == QMessageBox::Ok)
    {
        ui->listWidget_ProtocolItemList->takeItem(n);
        m_Protocol.removeItem(n);
    }


}

void MainWindow::on_actionSave_triggered()
{
    if(m_Protocol.strFileName().isEmpty())
    {
        on_actionSaveAs_triggered();
    }
    else
    {
        ProtocolItem item = ui->widget_PtotovolEditor->getProtocolItem();
        m_Protocol.setItem(ui->listWidget_ProtocolItemList->currentRow(), item);

        m_Protocol.save();

        QMessageBox::information(this, "提示", "文件保存成功!");
    }
}


void MainWindow::on_listWidget_ProtocolItemList_currentItemChanged(QListWidgetItem *current, QListWidgetItem *previous)
{
    if(previous)
    {
        int previous_row = ui->listWidget_ProtocolItemList->row(previous);
        if(previous_row >= 0)
        {
            ProtocolItem item = ui->widget_PtotovolEditor->getProtocolItem();
            m_Protocol.setItem(previous_row, item);
        }
    }

    if(current)
    {
        int current_row = ui->listWidget_ProtocolItemList->row(current);
        if(current_row >= 0)
        {
            ui->widget_PtotovolEditor->setProcotolItem(m_Protocol.itemAt(current_row));
            ui->widget_PtotovolEditor->setEnabled(true);
        }
    }
}

void MainWindow::on_actionSaveAs_triggered()
{
    QString fileName = QFileDialog::getSaveFileName(this, "选择保存路径", "", tr("GenFiles (*.xml)"));
    if(fileName.isEmpty())
    {
        return;
    }

    ProtocolItem item = ui->widget_PtotovolEditor->getProtocolItem();
    m_Protocol.setItem(ui->listWidget_ProtocolItemList->currentRow(), item);

    m_Protocol.save(fileName);

    QMessageBox::information(this, "提示", QString("%1 文件保存成功!").arg(fileName));

}

void MainWindow::on_actionSetting_triggered()
{
    SettingDialog settingDialog;
    settingDialog.setStrName(m_Protocol.strName());
    settingDialog.setStrAuthor(m_Protocol.strAuthor());
    settingDialog.setStrVersion(m_Protocol.strVersion());

    int res = settingDialog.exec();
    if(res == QFileDialog::Accepted)
    {
        m_Protocol.setStrName(settingDialog.strName());
        m_Protocol.setStrAuthor(settingDialog.strAuthor());
        m_Protocol.setStrVersion(settingDialog.strVersion());

        this->setWindowTitle(QString("%1-%2 (%3)")
                             .arg(m_Protocol.strName())
                             .arg(m_Protocol.strVersion())
                             .arg(m_Protocol.strFileName()));
    }
}

// 打开协议文件
void MainWindow::on_actionOpen_triggered()
{
    QString fileName = QFileDialog::getOpenFileName(this, "选择文件路径", "", tr("GenFiles (*.xml)"));
    if(fileName.isEmpty())
    {
        return;
    }

    openGenFile(fileName);
}

void MainWindow::protocolItemNameChanged(const QString name)
{
    QListWidgetItem* item = ui->listWidget_ProtocolItemList->currentItem();
    if(item)
    {
        item->setText(name);
    }
}

// 生成sdk
void MainWindow::on_actionGenSDK_triggered()
{
    json data;
    data["name"] = "world";
    std::string result = inja::render("hello {{ name }}", data);
    qDebug() << QString::fromStdString(result);
}

void MainWindow::refreshProtocolItemList()
{
    ui->listWidget_ProtocolItemList->clear();
    for(int i=0; i<m_Protocol.itemCount(); i++)
    {
        QString str = QString("%1(%2)")
                .arg(m_Protocol.itemAt(i).strNote)
                .arg(m_Protocol.itemAt(i).strName);
        ui->listWidget_ProtocolItemList->addItem(str);
    }

}

// bLoad 是否为初始化加载
void MainWindow::openGenFile(QString fileName, bool bLoad)
{
    if(m_Protocol.load(fileName))
    {
        refreshProtocolItemList();
    }
    else
    {
        if(bLoad)
        {
            m_Protocol.setStrAuthor("author");
            m_Protocol.setStrName("unNamed");
            m_Protocol.setStrVersion("1.0.0");
        }
    }

    this->setWindowTitle(QString("%1-%2 (%3)")
                         .arg(m_Protocol.strName())
                         .arg(m_Protocol.strVersion())
                         .arg(m_Protocol.strFileName()));

}
